<?php
namespace app\controller;

use app\BaseController;
use app\controller\model;
use liliuwei\think\Auth;
use think\facade\Session;
use think\facade\Db;
class Service extends BaseController
{
	protected $getpath="";
	protected $gobaluser="";
	protected $tables;
	public function __construct($check=true){
		if($check){
			checkuser();
			$this->gobaluser=Session::get("uid");
		}
		$this->tables=new model\Tables();
	}
	public function payMoneyGet2(){
		$id = request()->param("id");
		$payModel = new model\Service($id);
		$payModel->getPayMoney();
	}
	public function getTips(){
		$res = DB::name($this->tables->tips)->field("id as value,title,status")->where("cid",1)->select()->toArray();
		foreach ($res as &$v){
			if($v['status']!=1){
				$v['disabled']=true;
			}
		}

		echojson($res);
	}

	public function pushService($serviceID=0,$type='order',$order_no=''){
	    $log = new \app\Log("service_push");
		$service = DB::name($this->tables->service)->where("id",$serviceID)->find();
		if(!$service)return "服务商ID错误";
		$serviceUrl = $service['urlOrder'];
		if($serviceUrl=='' || $serviceUrl==null)return "缺失接口地址";
		if($type=='gas')$serviceUrl = $service['urlGas'];
		$time = time();
		$sgin = md5($service['username'].$time.$service['key']);
		$postArr = ['time'=>$time,'sign'=>$sgin];
		if($type=='order'){
			$serviceOrder = DB::name($this->tables->serviceOrder)->where("service_no",$order_no)->find();
			if(!$serviceOrder) return false;
			$temArr=[];
			$temArr['status']=$serviceOrder['reOrder'];
			if($serviceOrder['reOrder']==-1){
				$temArr['content']= $serviceOrder['reContent'];
			}
			$postArr['data']=json_encode($temArr);
			$postArr['service_no']=$order_no;

		}else{
			$postArr['gasID']=$order_no;
		}
		$re = curlPost($serviceUrl,$postArr);
		$log->write(['info'=>$service,'re'=>$re]);
		if($re=='success'){
			return true;
		}
		w_log($this->gobaluser,'服务商推送结果',"失败",$type,$re);
		return false;
	}
	public function payMoney(){
		$classesModel = new \app\controller\model\Classes();
		$service = $classesModel->rMyServiceToOption(0,DB::name($this->tables->service)->where("payType",1)->column("id"));
		return view("payMoney")->assign(['service'=>$service[0]]);
	}
	public function payMoneyGet(){
		$serviceID = request()->param("serviceID");
		$serviceID>0?$where="serviceID=$serviceID":$where='1=1';
		$res = getpagedata($this->tables->servicePayMoney,"",true,$where);
		$count = $res[1];
		$res = $res[0];
		$res = $res->all();
		foreach ($res as &$v){
			$v['serviceID'] = DB::name($this->tables->service)->where("id",$v['serviceID'])->column('title')[0];
		}
		pagejson($res,0,'',$count);
	}
	public function gasTips(){
		$tips = request()->param("tips");
		return view("gasTips")->assign(['tips'=>$tips]);
	}
	public function gasList(){
		$gasModel = new Gas();
		$inTips = request()->param("inTips");
		if($inTips=='' || $inTips==null)$inTips='0';
		$gasModel->gasList($inTips);
	}
	public function setGasSave(){
		$serviceID = request()->param("serviceID");
		$inGasTips = json_decode(request()->param("inGasTips"),true);
		$service = DB::name($this->tables->service)->where("id",$serviceID)->find();
		if(!$service)echojson([],1,'ID错误');
		if(is_array($inGasTips) && count($inGasTips)>0){
			$names = array_column($inGasTips, 'value');
			$inGasTips = implode(',', $names);
			$up = DB::name($this->tables->service)->where("id",$serviceID)->update(['inGasTips'=>$inGasTips]);
		}else{
			$up = DB::name($this->tables->service)->where("id",$serviceID)->update(['inGasTips'=>null]);
		}
		if(!$up)echojson([],1,'更新失败');
		echojson();
	}
	public function setGas(){
		$id = request()->param("id");
		$service = DB::name($this->tables->service)->where("id",$id)->find();
		if(!$service)echojson([],1,'ID错误');
		$service['inGasTips']="[".$service['inGasTips']."]";
		return view("setGas")->assign(['user'=>$service]);
	}
	public function task(){
		$classesModel = new \app\controller\model\Classes();
		return view("task")->assign(['tips'=>$classesModel->rTipsToOption('','',2)[0]]);
	}
	public function taskList(){
		$ctype = request()->param("ctype");
		$ctype>0?$where="ctype=$ctype":$where='1=1';
		$status = request()->param("status");
		$date1 = request()->param("date1");
		$date2 = request()->param("date2");
		$date3 = request()->param("date3");
		$date4 = request()->param("date4");
		if($date1!='' && $date2!=''){
			$where .= " and addTime>='$date1 00:00:00' and addTime<='$date2 23:59:59'";
		}
		if($date3!='' && $date4!=''){
			$where .= " and taskTime>='$date3 00:00:00' and taskTime<='$date4 23:59:59'";
		}
		$status==-1?$where.=" and status=-1":$where.=' and status>=0';
		$tips = request()->param("tips");
		$tips!=''?$where.=" and tipsID = $tips":'';
		$res = getpagedata($this->tables->taskService,"",true,$where);
		$count = $res[1];
		$res = $res[0];
		$res = $res->all();
		foreach ($res as $k=>$v){
			if($v['ctype']==1){
				$res[$k]['ctypeStr']='让利比例';
			}elseif($v['ctype']==2){
				$res[$k]['ctypeStr']='让利金额';
			}else{
				$res[$k]['ctypeStr']='选择油号';
			}
		}
		pagejson($res,0,'',$count);
	}

	public function taskAdd(){
		$classesModel = new \app\controller\model\Classes();
		$id = request()->param("id");
		$id<1?$id=0:'';
		$taskModel = new model\Task();
		if($id>0){
			$re = DB::name($this->tables->taskService)->where("id",$id)->find();
			if(!$re)echojson([],1,'ID错误');
			$re['tipsIDS']="[".$re['tipsIDS']."]";
			$re['tipsGasIDS']="[".$re['tipsGasIDS']."]";
			$re['inOilArr']=explode(",",$re['inOil']);
		}else{
			$re=[];
			$re['tipsIDS']="[]";
			$re['taskTime']=nowTime();
		}
		$tips = $classesModel->rTipsToOption('','',2);
		$tipsGas = $classesModel->rTipsToOption('','',1);

		return view("taskAdd")->assign(['data'=>$re,'tipsAllIDS'=>json_encode($tips[3]),'tipsAllGasIDS'=>json_encode($tipsGas[3])]);
	}
	public function taskSave(){
		$data = request()->param();
		unset($data['id']);
		$id = request()->param("id");
		$tipsIDS = request()->param("tipsIDS");
		$tipsGasIDS = request()->param("tipsGasIDS");
		$ctype = request()->param('ctype');
		foreach ($data as $v){
			if($v=='')echojson([],1,'所有必填');
		}
		if($tipsGasIDS!=''){
			$tipsGasIDS = array_column(json_decode($tipsGasIDS,true),'value');
			$data['tipsGasIDS'] = implode(",",$tipsGasIDS);
		}
		if($tipsIDS!=''){
			$tipsIDS = array_column(json_decode($tipsIDS,true),'value');
			$data['tipsIDS'] = implode(",",$tipsIDS);
		}
		if($id>0){
			$re = r_one($this->tables->taskService,"id=$id");
			if($re){
				DB::name($this->tables->taskService)->where("id",$id)->update($data);
				echojson([],0,'更新成功');
			}else{
				echojson([],1,'ID错误');
			}
		}else{
			$data['addTime']=nowTime();

			$re = DB::name($this->tables->taskService)->insert($data);
			if($re){
				echojson([],0,'添加成功');
			}else{
				echojson([],1,'ID错误');
			}
		}
	}




	public function rechargeAdmin(){
		return view("service/rechargeAdmin");
	}
	public function tipsSaveIDS(){
		$tipsID = request()->param("tipsID");
		$checkIds = json_decode(request()->param("checkIds"),true);
		$re =DB::name($this->tables->service)->whereIn("id",$checkIds)->update(['tipsID'=>$tipsID]);
		if(!$re)echojson([],1,'更新失败');
		echojson();
	}
	public function rechargeAdminSave(){
		$id = request()->param("id");
		$confirm = request()->param("confirm");
		$content = request()->param("content");
		if($confirm == 'false'){
			if($content=='')echojson([],1,'原因不可为空');
			$up = DB::name($this->tables->serviceAmount)->where("id",$id)->where("status",0)->update(['status'=>-1,'content'=>$content]);
			if(!$up)echojson([],1,'不可更新');
			echojson();
		}
		lock();
		$log = DB::name($this->tables->serviceAmount)->where("id",$id)->lock(true)->find();
		if($log && $log['status']==0){
			$user =  DB::name($this->tables->service)->where("id",$log['serviceID'])->lock(true)->find();
			if(!$user)echojson([],1,'充值用户错误');
			$amountEnd = bcadd($user['amount'],$log['amount'],2);
			$up = ['admin2ID'=>$this->gobaluser,'startAmount'=>$user['amount'],'endAmount'=>$amountEnd,'adminTime'=>nowTime(),'status'=>1];
			$re = DB::name($this->tables->serviceAmount)->where("id",$id)->update($up);
			if(!$re) echojson([],1,'添加失败:1');
			$userUp = DB::name($this->tables->service)->where("id",$log['serviceID'])->update(['amount'=>$amountEnd]);
			if(!$userUp) echojson([],1,'添加失败:2');
			echojson();
		}
		echojson([],1,'订单错误');
	}
	public function rechargeAdminList(){
		$page = request()->param("page");
		$title = request()->param("title");
		$serviceID = request()->param("serviceID");
		$mobile = request()->param("mobile");
		$contacts = request()->param("contacts");
		$admin = request()->param("admin");
		$admin2 = request()->param("admin2");
		$status = request()->param("status");
		$limit = request()->param("limit");
		$where="1=1";
		if($title!=''){
			$users = DB::name($this->tables->service)->where("title","like","%$title%")->column("id");
			if($users){
				if(count($users)>50) echojson([],1,'名称关键词太短');
				$where .= " and serviceID in (".implode(",",$users).")";
			}else{
				$where .= " and serviceID < 0";
			}
		}
		if($mobile!=''){
			$users = DB::name($this->tables->service)->where("mobile","like","%$mobile%")->column("id");
			if($users){
				if(count($users)>50) echojson([],1,'手机关键词太短');
				$where .= " and serviceID in (".implode(",",$users).")";
			}else{
				$where .= " and serviceID < 0";
			}
		}
		if($contacts!=''){
			$users = DB::name($this->tables->service)->where("contacts","like","%$contacts%")->column("id");
			if($users){
				if(count($users)>50) echojson([],1,'联系人关键词太短');
				$where .= " and serviceID in (".implode(",",$users).")";
			}else{
				$where .= " and serviceID < 0";
			}
		}
		if($serviceID>0)$where .= " and serviceID = $serviceID";
		if($admin>0){
			$where .= " and adminID = $admin";
		}
		if($admin2>0){
			$where .= " and admin2ID = $admin2";
		}
		if($status != ''){
			$where .= " and status = $status";
		}
		$list = getpagedata($this->tables->serviceAmount,"",true,$where);
		$count = $list[1];
		$list = $list[0]->all();
		$admins = r_users();
		$pays = r_classes(279);
		foreach ($list as $k => $v){
			$list[$k]['uid'] = serviceIDToName($v['serviceID']);
			$list[$k]['gasID'] = gasIDToName($v['gasID']);
			$list[$k]['supplierID'] = supplierIDToTitle($v['supplierID']);
			$list[$k]['adminID'] = adminIDToUserName($admins,$v['adminID']);
			$list[$k]['admin2ID'] = adminIDToUserName($admins,$v['admin2ID']);
			$list[$k]['pays'] = rclasstitle($pays,$v['pays']);
		}
		pagejson($list,0,'',$count);
	}
	public function rechargeAdmin2(){
		$userID = request()->param("userID");
		$re=[];
		if($userID>0){
			$re = DB::name($this->tables->service)->where("id",$userID)->find();
			$re['amount']='';
		}else{
			echojson([],1,'ID错误');
		}
		$classModel = new \app\controller\model\Classes();
		return view("service/rechargeAdmin2")->assign(['data'=>$re,'pays'=>$classModel->rClassessToOption(279)]);
	}
	public function rechargeAdmin2Save($data=[],$return=false){
		isset($data['userID']) && $data['userID']>0?$userID=$data['userID']:$userID = request()->param("userID");
		isset($data['content']) && $data['content']!=''?$content=$data['content']:$content = request()->param("content");
		isset($data['img1']) && $data['img1']!=''?$img=$data['img1']:$img = request()->param("img");
		isset($data['amount']) && $data['amount']!=''?$amount=$data['amount']:$amount = request()->param("amount");
		isset($data['pays']) && $data['pays']!=''?$pays=$data['pays']:$pays = request()->param("pays");
		if($userID<1 || $img=='' || abs($amount)==0 || $pays<1) echojson([],1,"所有项必填");
		lock();
		$user = DB::name($this->tables->service)->where("id",$userID)->lock(true)->find();
		if(!$user) echojson([],1,'ID错误');
		$amountEnd = bcadd($user['amount'],$amount,2);
		$up = [
			'adminID'=>$this->gobaluser,
			'serviceID'=>$user['id'],
			'startAmount'=>$user['amount'],
			'endAmount'=>$amountEnd,
			'amount'=>$amount,
			'content'=>$content,
			'adminImg'=>$img,
			'addTime'=>nowTime(),
			'pays'=>$pays
		];
		$re = DB::name($this->tables->serviceAmount)->insert($up);
		if(!$re) echojson([],1,'添加失败:1');
		if($return)return true;
		echojson();
	}
	public function list(){
		$classesModel = new \app\controller\model\Classes();
		return view("list")->assign(['cids'=>$classesModel->rClassessToOption(273),'tips'=>$classesModel->rTipsToOption('','',2)[0]]);
	}
	public function listEdit(){
		$id = request()->param("id");
		$id<1?$id=0:'';
		if($id>0){
			$re = DB::name($this->tables->service)->where("id",$id)->find();
		}else{
			return "信息错误";
		}
		if(!$re)echojson([],1,'ID错误');
		$gasModel = new model\Gas($id);
		$re['prices'] = $gasModel->getGasPrice();
		return view("price")->assign(['data'=>$re]);
	}
	public function gasLocalSave(){
		$id = request()->param("id");
		if($id>0){
			$re = DB::name($this->tables->service)->where("id",$id)->find();
		}else{
			return "信息错误";
		}
		if(!$re)echojson([],1,'ID错误');
		$gasModel = new model\Gas($id);
		$gasModel->SaveGasPrice(request()->param("data"));
	}
	public function listAdd(){
		$id = request()->param("id");
		$id<1?$id=0:'';
		if($id>0){
			$re = DB::name($this->tables->service)->where("id",$id)->find();
		}else{
			$re = ['cids'=>0];
		}
		$classesModel = new model\Classes();
		return view("listAdd")->assign(['data'=>$re,'cids'=>$classesModel->rClassessToOption(273,$re['cids'])]);
	}
	public function listGet(){
		$cids = request()->param("cids");
		$cids>0?$where="cids=$cids":$where='1=1';
		$status = request()->param("status");
		$status==-1?$where.=" and status=-1":'';
		$name = request()->param("name");
		$name!=''?$where.=" and title like '%$name%'":'';
		$res = getpagedata($this->tables->service,"",true,$where);
		$count = $res[1];
		$res = $res[0]->all();
		$cids = r_classes(273);
		$classesModel = new model\Classes();
		$tipsArr = $classesModel->rTipsToOption('','',2)[2];
		foreach ($res as $k=>$v){
			$res[$k]['cids']=rclasstitle($cids,$v['cids']);
			$res[$k]['tipsID']=rclasstitle($tipsArr,$v['tipsID']);
		}
		pagejson($res,0,'',$count);
	}
	public function listSave(){
		$data = request()->param();
		unset($data['id']);
		$id = request()->param("id");
		$field = request()->param('field');
		if(in_array($field,['subPercent','subPrice','status'])){
			$value = request()->param('value');
			$uparr = ["$field"=>$value];
			if($field=='status' && $value==-1){
				$content = request()->param("content");
				if($content=='')echojson([],1,'原因必填');
				$uparr['content']=$content;
			}
			DB::name($this->tables->service)->where("id",$id)->update($uparr);
			echojson([],0,'更新成功');
		}
		foreach ($data as $k => $v){
			if($k=='subPercent' || $k=='subPrice'){
				continue;
			}
			if($v=='')echojson([],1,'所有必填');
		}
		$username = $data['username'];
		if($id>0){
			$re = DB::name($this->tables->service)->where("id",$id)->find();
			if($re){
				if($re['username']!=$username){
					$one = DB::name($this->tables->service)->where('username',$username)->find();
					if($one)echojson([],1,'用户名重复');
				}
				DB::name($this->tables->service)->where("id",$id)->update($data);
				echojson([],0,'更新成功');
			}else{
				echojson([],1,'ID错误');
			}
		}else{
			$data['addTime']=nowTime();
			$one = DB::name($this->tables->service)->where('username',$username)->find();
			if($one)echojson([],1,'用户名重复');
			$re = DB::name($this->tables->service)->insert($data);
			if($re){
				echojson([],0,'添加成功');
			}else{
				echojson([],1,'ID错误');
			}
		}
	}

	/**设置油站和服务商的折扣，percent=0表示删除
	 * @param $gasID
	 * @param $servicerID
	 * @param $percent
	 * @return bool
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\DbException
	 * @throws \think\db\exception\ModelNotFoundException
	 */
	public function setGasServicePrice($gasID,$servicerID,$percent=0){
		$gas = DB::name($this->tables->gas)->where("id",$gasID)->find();
		if(!$gas) return false;
		if($gas['servicePrice']=='' || $gas['servicePrice']==null){
			$servicePrice=[];
		}else{
			$servicePrice = explode(",",$gas['servicePrice']);
		}
		if($percent==0){
			$upGas = DB::name($this->tables->gasServicePrice)->where("gasID",$gasID)->where("serviceID",$servicerID)->delete();
			if($upGas){
				$key = array_search($servicerID, $servicePrice);
				if ($key !== false) unset($servicePrice[$key]);
				DB::name($this->tables->gas)->where("id",$gasID)->update(['servicePrice'=>implode(',',$servicePrice)]);
			}
		}else{
			$re = DB::name($this->tables->gasServicePrice)->where("gasID",$gasID)->where("serviceID",$servicerID)->find();
			if($re){
				DB::name($this->tables->gasServicePrice)->where("id",$re['id'])->update(['percent'=>$percent]);
			}else{
				$insert = DB::name($this->tables->gasServicePrice)->insert(['percent'=>$percent,'gasID'=>$gasID,'serviceID'=>$servicerID]);
				if($insert){
					$servicePrice[] = $servicerID;
					DB::name($this->tables->gas)->where("id",$gasID)->update(['servicePrice'=>implode(',',$servicePrice)]);
				}
			}
		}
		return true;
	}

}
